import React, { useMemo, useState } from 'react';
import { Card, Space, Button, Table, Modal, Form, Input, Select, InputNumber, Tag, message, Switch } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

// 本地存储键名
const LS_KEY = 'authority-menu-tree';

// 菜单类型字典
const TYPE_OPTIONS = [
  { label: '目录', value: 0 },
  { label: '菜单', value: 1 },
  { label: '按钮', value: 2 },
];

function humpToLine(str = '') {
  return str
    .replace(/([A-Z])/g, '-$1')
    .replace(/^-/, '')
    .toLowerCase();
}

function genInitialTree() {
  const now = new Date();
  const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  return [
    {
      id: 1,
      name: '系统管理',
      icon: 'el-icon-setting',
      type: 0,
      component: 'System',
      authority: 'sys:root',
      url: '/system',
      path: '/system',
      enabled: '1',
      sort: 1,
      pId: '0',
      createTime: fmt(now),
      children: [
        {
          id: 11,
          name: '菜单管理',
          icon: 'el-icon-menu',
          type: 1,
          component: 'AuthorityMenu',
          authority: 'sys:menu:list',
          url: '/authority/menu',
          path: '/authority/menu',
          enabled: '1',
          sort: 1,
          pId: '1',
          createTime: fmt(now),
        },
      ],
    },
    {
      id: 2,
      name: '权限管理',
      icon: 'el-icon-lock',
      type: 0,
      component: 'Authority',
      authority: 'sys:authority',
      url: '/authority',
      path: '/authority',
      enabled: '1',
      sort: 2,
      pId: '0',
      createTime: fmt(now),
    },
  ];
}

function loadFromLS() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return genInitialTree();
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : genInitialTree();
  } catch (e) {
    return genInitialTree();
  }
}

function saveToLS(list) {
  localStorage.setItem(LS_KEY, JSON.stringify(list));
}

export default function MenuPage() {
  const [menuList, setMenuList] = useState(() => loadFromLS());
  const [loading, setLoading] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [parentId, setParentId] = useState('0');
  const [form] = Form.useForm();

  const columns = [
    { title: '名称', dataIndex: 'name', key: 'name', width: 250 },
    { title: '图标', dataIndex: 'icon', key: 'icon', width: 120, align: 'center', render: (v) => <span>{v}</span> },
    { title: '类型', dataIndex: 'type', key: 'type', width: 100, align: 'center', render: (v) => v === 0 ? <Tag>目录</Tag> : v === 1 ? <Tag color="green">菜单</Tag> : <Tag color="orange">按钮</Tag> },
    { title: '组件', dataIndex: 'component', key: 'component', width: 160, align: 'center' },
    { title: '权限标识', dataIndex: 'authority', key: 'authority', width: 220, align: 'center' },
    { title: '菜单URL', dataIndex: 'url', key: 'url', width: 200, align: 'center' },
    {
      title: '完整路径', key: 'path', width: 260, align: 'center',
      render: (_, r) => (r.path && r.component ? `${r.path}/${humpToLine(r.component)}` : r.path || '-')
    },
    {
      title: '显示', dataIndex: 'enabled', key: 'enabled', width: 100, align: 'center',
      render: (_, r) => (
        <Tag color={String(r.enabled) === '1' ? 'success' : 'warning'} onClick={() => tagEnabled(r)} style={{ cursor: 'pointer' }}>
          {String(r.enabled) === '1' ? '启用' : '禁用'}
        </Tag>
      )
    },
    { title: '排序', dataIndex: 'sort', key: 'sort', width: 100, align: 'center' },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 160, align: 'center' },
    {
      title: '操作', key: 'actions', fixed: 'right', width: 210, align: 'center',
      render: (_, row) => (
        <Space>
          <Button size="small" onClick={() => onEdit(row)} icon={<EditOutlined />}>编辑</Button>
          <Button size="small" type="primary" disabled={row.type === 2} onClick={() => onAppend(row)} icon={<PlusOutlined />}>添加</Button>
          <Button size="small" danger onClick={() => onDelete(row)} icon={<DeleteOutlined />}>删除</Button>
        </Space>
      )
    },
  ];

  const onAppendRoot = () => {
    setIsEdit(false);
    setParentId('0');
    form.resetFields();
    form.setFieldsValue({ type: 0, enabled: '1' });
    setDialogOpen(true);
  };

  const onAppend = (row) => {
    if (row.type === 2) {
      message.warning('按钮不支持添加子级');
      return;
    }
    setIsEdit(false);
    setParentId(String(row.id));
    form.resetFields();
    form.setFieldsValue({ type: 1, enabled: '1', sort: (row.children?.length || 0) + 1 });
    setDialogOpen(true);
  };

  const onEdit = (row) => {
    setIsEdit(true);
    setParentId(String(row.pId ?? '0'));
    form.setFieldsValue({
      id: row.id,
      name: row.name,
      icon: row.icon,
      type: row.type,
      component: row.component,
      authority: row.authority,
      url: row.url,
      path: row.path,
      enabled: String(row.enabled),
      sort: row.sort,
    });
    setDialogOpen(true);
  };

  const onDelete = (row) => {
    Modal.confirm({
      title: '确认删除此菜单？',
      content: `将删除：${row.name}${row.children ? ' 及其所有子菜单' : ''}`,
      okText: '删除',
      okButtonProps: { danger: true },
      onOk: () => {
        const removeNode = (arr, id) => arr.filter((n) => {
          if (Array.isArray(n.children)) n.children = removeNode(n.children, id);
          return n.id !== id;
        });
        const newList = removeNode([...menuList], row.id);
        setMenuList(newList);
        saveToLS(newList);
        message.success('已删除');
      }
    });
  };

  const tagEnabled = (row) => {
    const enabled = String(row.enabled) === '1' ? '0' : '1';
    const text = enabled === '1' ? '显示' : '隐藏';
    Modal.confirm({
      title: '提示',
      content: `${text}${row.pId === '0' ? '（包含所有子菜单）' : ''}`,
      onOk: () => {
        const updateEnabled = (arr) => arr.map((n) => {
          if (n.id === row.id) {
            return { ...n, enabled };
          }
          if (row.pId === '0' && n.pId === '0' && n.id === row.id && Array.isArray(n.children)) {
            // 根菜单批量应用示例（此处仅演示，实际可递归）
            const children = n.children.map((c) => ({ ...c, enabled }));
            return { ...n, enabled, children };
          }
          if (Array.isArray(n.children)) return { ...n, children: updateEnabled(n.children) };
          return n;
        });
        const newList = updateEnabled([...menuList]);
        setMenuList(newList);
        saveToLS(newList);
        message.success('状态已更新');
      }
    });
  };

  const onModalOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const now = new Date();
      const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
      let newList = [...menuList];
      if (isEdit && values.id) {
        const updateNode = (arr) => arr.map((n) => {
          if (n.id === values.id) {
            return { ...n, ...values };
          }
          if (Array.isArray(n.children)) return { ...n, children: updateNode(n.children) };
          return n;
        });
        newList = updateNode(newList);
        message.success('已更新菜单');
      } else {
        const newNode = {
          id: Date.now(),
          pId: parentId,
          name: values.name,
          icon: values.icon,
          type: values.type ?? 1,
          component: values.component,
          authority: values.authority,
          url: values.url,
          path: values.path || (values.url ? values.url : ''),
          enabled: values.enabled ?? '1',
          sort: values.sort ?? 1,
          createTime: fmt(now),
        };
        if (parentId && parentId !== '0') {
          const addChild = (arr) => arr.map((n) => {
            if (String(n.id) === String(parentId)) {
              const children = Array.isArray(n.children) ? [...n.children, newNode] : [newNode];
              return { ...n, children };
            }
            if (Array.isArray(n.children)) return { ...n, children: addChild(n.children) };
            return n;
          });
          newList = addChild(newList);
        } else {
          newList.push(newNode);
        }
        message.success('已新增菜单');
      }
      setMenuList(newList);
      saveToLS(newList);
      setDialogOpen(false);
    } catch (e) {
      // 校验失败
    } finally {
      setLoading(false);
    }
  };

  const onModalCancel = () => setDialogOpen(false);

  return (
    <Card title="菜单管理" extra={<Space><Button type="primary" icon={<PlusOutlined />} onClick={onAppendRoot}>添加菜单</Button></Space>}>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={menuList}
        loading={loading}
        pagination={false}
        expandable={{ defaultExpandAllRows: true }}
        scroll={{ y: 560, x: 1200 }}
      />

      <Modal
        title={isEdit ? '修改菜单' : '添加菜单'}
        open={dialogOpen}
        onOk={onModalOk}
        onCancel={onModalCancel}
        okText={isEdit ? '保存' : '新增'}
        confirmLoading={loading}
        destroyOnClose
        width={720}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="id" noStyle>
            <Input type="hidden" />
          </Form.Item>
          <Form.Item label="父级菜单 ID" tooltip="新增为根菜单时留空" >
            <Input value={parentId} disabled />
          </Form.Item>
          <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder="例如：菜单管理" />
          </Form.Item>
          <Form.Item label="图标类名" name="icon">
            <Input placeholder="例如：el-icon-menu" />
          </Form.Item>
          <Form.Item label="类型" name="type" rules={[{ required: true, message: '请选择类型' }]}>
            <Select options={TYPE_OPTIONS} placeholder="请选择" />
          </Form.Item>
          <Form.Item label="组件名" name="component">
            <Input placeholder="例如：AuthorityMenu" />
          </Form.Item>
          <Form.Item label="权限标识" name="authority">
            <Input placeholder="例如：sys:menu:list" />
          </Form.Item>
          <Form.Item label="菜单URL" name="url">
            <Input placeholder="例如：/authority/menu" />
          </Form.Item>
          <Form.Item label="完整路径" name="path">
            <Input placeholder="例如：/authority/menu" />
          </Form.Item>
          <Form.Item label="是否显示" name="enabled" initialValue={'1'}>
            <Select options={[{ label: '启用', value: '1' }, { label: '禁用', value: '0' }]} />
          </Form.Item>
          <Form.Item label="排序" name="sort">
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}